package web.login;

import application.MySession;
import application.authorization.RolesSession;
import domain.User;
import org.apache.wicket.Application;
import org.apache.wicket.markup.html.form.*;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.value.ValueMap;
import service.facade.user.UserService;
import web.admin.AdminPage;


public class SignPanel extends Panel {
    @SpringBean
    private UserService userService;
    @SpringBean(name = "mySession")
    private MySession mySession;

    /**
     * True if logged user is admin. This variable should be setted in singIn method after login.
     */
    protected Boolean isLoggedUserAdmin;

    /**
     * Constructor.
     *
     * @param id component id
     */
    public SignPanel(final String id) {
        super(id);
        add(new SignInForm("signInForm").setOutputMarkupId(false));
    }

    /**
     * The actual login process.
     *
     * @param userName
     * @param password
     * @return true, if the login was successful, false otherwise
     */
    public boolean signIn(String userName, String password) throws AccountIsNotActivatedException, Exception {

        RolesSession waspSession = ((RolesSession) getSession());
//        if (waspSession.logoff()) {
//        waspSession.invalidateNow();
        waspSession.signOut();
//        waspSession.clear();

//        }
        RolesSession rolesSession = (RolesSession) getSession();
        if (rolesSession.signIn(userName, password)) {
            User user = rolesSession.getUser();
            mySession.setId(user.getId());
            if (user != null && user.isAdmin()) {
                isLoggedUserAdmin = true;
            } else {
                isLoggedUserAdmin = false;
            }
            return true;
        }
        return false;

    }

    /**
     * Sign in form.
     */
    public final class SignInForm extends StatelessForm {

        private static final long serialVersionUID = 1L;
        /**
         * remember Customer name
         */
        private boolean rememberMe = true;

        /**
         * Constructor.
         *
         * @param id id of the form component
         */
        public SignInForm(final String id) {
            super(id, new CompoundPropertyModel<ValueMap>(new ValueMap()));

            // only remember Customer name, not passwords
            add(new TextField<String>("login").setType(String.class).setPersistent(rememberMe).setOutputMarkupId(false));
            add(new PasswordTextField("password").setType(String.class).setOutputMarkupId(false));
            add(new CheckBox("rememberMe", new PropertyModel(this, "rememberMe")));
        }

        /**
         * @see org.apache.wicket.Component#getMarkupId()
         */
        @Override
        public String getMarkupId() {
            // fix javascript id
            return getId();
        }

        /**
         * @see org.apache.wicket.markup.html.form.Form#onSubmit()
         */
        @Override
        public final void onSubmit() {

            if (!rememberMe) {
                // delete persistent data
                getPage().removePersistedFormData(SignInForm.class, true);
            }

            ValueMap values = (ValueMap) getModelObject();
            String login = values.getString("login");
            String password = values.getString("password");

            try {
                if (signIn(login, password)) {
                    getSession().info(getLocalizer().getString("login.success", this));

                    //if just logged user is admin, response page should be admin menu
                    if (isLoggedUserAdmin) {
                        setResponsePage(AdminPage.class);
                    }
                    // continue or homepage?
                    else if (!getPage().continueToOriginalDestination()) {
                        setResponsePage(Application.get().getHomePage());
                    }
                    //                }
                } else {
                    getSession().error(getLocalizer().getString("login.fail.login", this));
                }
            } catch (AccountIsNotActivatedException e) {
                //OK
                if (!getPage().continueToOriginalDestination()) {
                    setResponsePage(Application.get().getHomePage());
                }
                System.err.println("AccountIsNotActivatedException e");
            } catch (Exception e) {
                error(getLocalizer().getString("login.fail.error", this));
                e.printStackTrace();
            }
        }

        /**
         * @return true if formdata should be made persistent (cookie) for later
         *         logins.
         */
        public boolean getRememberMe() {
            return rememberMe;
        }

        /**
         * Remember form values for later logins?.
         *
         * @param rememberMe true if formdata should be remembered
         */
        public void setRememberMe(boolean rememberMe) {
            this.rememberMe = rememberMe;
            ((FormComponent) get("login")).setPersistent(rememberMe);
        }
    }


}
